package com.gzx.spring.db.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzx.risk.core.pojo.UserInfo;
import com.gzx.risk.core.service.OrderOpService;
import com.gzx.spring.db.entity.PhoneProductOrder;
import com.gzx.spring.db.entity.RiskRuleResult;
import com.gzx.spring.db.pojo.OrderReviewInfo;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class OrderReviewService {
	@Resource
	private RiskRuleResultService riskRuleResultService;
	@Resource
	private PhoneProductOrderService phoneProductOrderService;
	@Resource
	private PhoneUserService phoneUserService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private OrderOpService orderOpService;

	public List<OrderReviewInfo> getOrders() {
		Map<String, String> codeMap = sysDictItemService.getCodeMap("orderStatusLabel");

		List<OrderReviewInfo> infos = Lists.newArrayList();

		QueryWrapper<RiskRuleResult> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNull("review_result")
                .eq("rule_result", "true")
                .eq("risk_node",2)
                .orderByAsc("created_time");

		List<RiskRuleResult> datas = riskRuleResultService.list(queryWrapper);
		log.info("datas:{}", datas.size());
		for (RiskRuleResult data : datas) {
			PhoneProductOrder phoneProductOrder = phoneProductOrderService.getOrder(data.getOrdercode());
			if (phoneProductOrder == null) {
				log.info("NotFound ordercode:{}", data.getOrdercode());
				continue;
			} 
			// 订单关闭
			if (phoneProductOrder.getStatus() == 9 || phoneProductOrder.getStatus() == 10
					|| phoneProductOrder.getStatus() == 11 || phoneProductOrder.getStatus() == 12) {
				data.setReviewResult("false");
				riskRuleResultService.updateById(data);// 关闭订单，直接算审核拒绝
				continue;
			}
			// 待归还，归还中
			if (phoneProductOrder.getStatus() == 5 || phoneProductOrder.getStatus() == 6) {
				data.setReviewResult("true");
				riskRuleResultService.updateById(data);// 直接算审核通过
				continue;
			}
            OrderReviewInfo info = new OrderReviewInfo();
			info.setOrdercode(phoneProductOrder.getOrdercode());
			updateStatus(codeMap, phoneProductOrder.getStatus(), info);
			info.setLeaseTerm(phoneProductOrder.getLeaseTerm());

			info.setPhone(data.getPhone());
			info.setName(data.getName());
			info.setIdCard(data.getIdCard());
			String createdTime = DateUtils.format(data.getCreatedTime(), DateUtils.DATE_FORMAT_19);
			info.setCreatedTime(createdTime);

			infos.add(info);
		}
		return infos;
	}

	public OrderReviewInfo getOrder(String ordercode) {
		RiskRuleResult reultInfo = riskRuleResultService.getByOrdercode(ordercode);
		Map<String, String> codeMap = sysDictItemService.getCodeMap("orderStatusLabel");
		PhoneProductOrder order = phoneProductOrderService.getOrder(ordercode);

		JSONObject obj = StringUtils.isNotBlank(order.getParams()) ? JSONObject.parseObject(order.getParams())
				: new JSONObject();
		UserInfo userInfo = phoneUserService.getUser(order.getUid());
		OrderReviewInfo info = new OrderReviewInfo();
		info.setOrdercode(order.getOrdercode());
		updateStatus(codeMap, order.getStatus(), info);

		info.setLeaseTerm(order.getLeaseTerm());

		info.setPhone(userInfo.getPhone());
		info.setName(userInfo.getName());
		info.setIdCard(userInfo.getId());

		info.setPhoneType(obj.getString("title"));
		info.setYushouCount(String.valueOf(reultInfo.getYushouCount() + 1));
		JSONArray arr = obj.getJSONArray("orderPriceList");
		if (arr != null && arr.size() > 0) {
			double price = 0.0;
			for (int i = 0; i < Math.min(reultInfo.getYushouCount() + 1, arr.size()); i++) {
				price += Double.valueOf(arr.getJSONObject(i).getString("price"));
			}
			info.setFirstPrice(String.valueOf(price));
		}

		if (arr != null && arr.size() > reultInfo.getYushouCount() + 1) {
			info.setMonthPrice(arr.getJSONObject(reultInfo.getYushouCount() + 1).getString("price"));
		}
		String recvAddress = order.getProvince() + order.getCity() + order.getDistrict() + order.getAddress();
		info.setRecvAddress(recvAddress);
		info.setRecvPhone(order.getPhone());
		info.setRecvName(order.getTit());
		return info;
	}

	private void updateStatus(Map<String, String> codeMap, Integer status, OrderReviewInfo info) {
		if (codeMap.containsKey(String.valueOf(status))) {
			info.setStatus(codeMap.get(String.valueOf(status)));
		} else {
			info.setStatus(String.valueOf(status));
		}
	}

	/**
	 * 信审通过
	 */
	public void permit(String ordercode) {
		List<RiskRuleResult> resultList = riskRuleResultService.getListByOrdercode(ordercode);
        for (RiskRuleResult reultInfo : resultList) {
            reultInfo.setReviewResult("true");
            riskRuleResultService.updateById(reultInfo);
        }
		PhoneProductOrder order = phoneProductOrderService.getOrder(ordercode);
		orderOpService.permit(order.getId());
	}

	/**
	 * 信审不通过
	 */
	public void reject(String ordercode) {
        List<RiskRuleResult> resultList = riskRuleResultService.getListByOrdercode(ordercode);
        for (RiskRuleResult reultInfo : resultList) {
            reultInfo.setReviewResult("false");
            riskRuleResultService.updateById(reultInfo);
        }
		PhoneProductOrder order = phoneProductOrderService.getOrder(ordercode);
		orderOpService.reject(order.getId());
	}
}
